﻿var vm = new Vue({
    el: '#container'
    , data: {
        buttons: {}
        , query: {
            menu_name: ''
        }
        , selected: {
            rows: []
        }
        , actionInfo: {
            data: []
            , value: []
            , visible: false
            , menuNo: ''
            , menuName: ''
        }
        , tableData: {
            records: []
            , total: 0
        }
        , edit: {
            formId: 'editFrame'
            , title: '操作'
            , visible: false
            , fields: [{
                label: '菜单编号'
                , name: 'menu_no'
                , type: 'hidden'
                , value: ''
            },{
                label: '上级菜单'
                , name: 'menu_pno'
                , require: true
                , type: 'select'
                , disabled: false
                , value: ''
                , rules: {
                    required: true, message: '请选择上级菜单', trigger: 'blur'
                }
                , options: []
            }, {
                label: '菜单名称'
                , name: 'menu_name'
                , require: true
                , type: 'text'
                , disabled: false
                , value: ''
                , rules: {
                    required: true, message: '请输入菜单名称', trigger: 'blur'
                }
            }, {
                label: '菜单Icon'
                , name: 'menu_icon'
                , require: false
                , type: 'text'
                , disabled: false
                , value: ''
            }, {
                label: '菜单Url'
                , name: 'menu_url'
                , type: 'text'
                , disabled: false
                , value: ''
            }, {
                label: '同级排序'
                , name: 'menu_orderby'
                , type: 'number'
                , disabled: false
                , value: 1
                }]
            , optype: ''
            , op: function () { }
        }
    }
    , mounted: async function () {
        let me = this;
        me.buttons = await hcCore.getPowerButton();
        if (me.buttons.hasQuery) {
            me.onQuery();
        }
        this.getActionInfo();
    }
    , computed: {
        menuOptions: function () {
            let optionArr = [];
            optionArr.push({
                value: '-'
                , label: '根菜单'
            });
            this.buildMenus(this.tableData.records, optionArr, 1);
            return optionArr;
        }
    }
    , methods: {
        handleButton: function (actNo, row) {
            switch (actNo) {
                case 'Query':
                    this.onQuery();
                    break;
                case 'Add':
                    this.showEdit('add', '新增');
                    break;
                case 'Edit':
                    this.showEdit('edit', '编辑', row);
                    break;
                case 'Action':
                    this.onPower(row);
                    break;
                case 'Delete':
                    this.onDelete(row);
                    break;
                    break;
                default:
                    break;
            }
        }
        , onQuery: function () {
            let me = this;
            hcCore.post({
                url: '/SysMenu/Tree'
                , param: { p_no: '-' }
                , success: function (rsp) {
                    me.tableData.records = rsp.data;
                }
            })
        }
        , showEdit: async function (type, title, row) {
            let me = this;
            me.resetParams(me.edit.fields);
            me.edit.title = title;
            me.edit.optype = type;
            me.edit.op = type == 'add' ? me.onInsert : (type == 'edit' ? me.onUpdate : function () { });
            me.edit.fields[1].options = me.menuOptions;
            if (type == 'edit') {
                if (row) {
                    await hcCore.post({
                        url: '/SysMenu/Get/' + row.menu_no
                        , success: function (rsp) {
                            me.edit.fields.forEach((item, index) => {
                                item.value = rsp.data[item.name];
                            });
                        }
                        , fault: '获得数据失败'
                    });
                }
                else {
                    hcCore.showError('请选择要编辑的记录');
                    return;
                }
            }
            me.edit.visible = true;
        }
        , onInsert: function () {
            let me = this;
            me.$refs.edit.$refs[me.edit.formId].validate((valid) => {
                if (valid) {
                    hcCore.post({
                        url: '/SysMenu/Insert'
                        , param: me.getParams()
                        , success: function (rsp) {
                            hcCore.showSuccess('新增成功');
                            //let records = me.tableData.records;
                            me.insertRecord(me.tableData.records, rsp.data);
                            me.tableData.total += 1;
                            me.edit.visible = false;
                        }
                    });
                } else {
                    return false;
                }
            });
        }
        , onUpdate: function () {
            let me = this;
            me.$refs.edit.$refs[me.edit.formId].validate((valid) => {
                if (valid) {
                    hcCore.post({
                        url: '/SysMenu/Update'
                        , param: me.getParams()
                        , success: function (rsp) {
                            hcCore.showSuccess('更新成功');
                            me.$refs.tblRecords.clearSelection();
                            let row = me.getSelectedRecord(me.tableData.records, rsp.data.menu_no);
                            rsp.data.children = row.children;
                            me.removeSelectedRecords(me.tableData.records, [rsp.data.menu_no]);
                            me.insertRecord(me.tableData.records, rsp.data);
                            me.edit.visible = false;
                        }
                    });
                } else {
                    return false;
                }
            });
        }
        , onDelete: function (row) {
            let me = this;
            let rows = [];
            if (row) {
                rows = [row];
            }
            else {
                rows = me.$refs.tblRecords.selection;
            }
            if (rows) {
                hcCore.confirm('删除记录及其所有子记录都会被删除，确认要删除选择的记录吗？', function () {
                    let recordArr = rows.map(item => { return item.menu_no });
                    let recordNos = recordArr.join(',');
                    hcCore.post({
                        url: '/SysMenu/Delete'
                        , param: {
                            user_nos: recordNos
                        }
                        , success: function (rsp) {
                            hcCore.showSuccess('删除成功');
                            me.tableData.total += recordArr.length;
                            me.removeSelectedRecords(me.tableData.records, recordArr);
                        }
                    });
                });
            }
            else {
                hcCore.showError('请选择要删除的记录');
            }
        }
        , onPower: function (row) {
            let me = this;
            if (!row) {
                hcCore.showError('请选择要操作的记录');
                return;
            }
            me.actionInfo.menuNo = row.menu_no;
            me.actionInfo.menuName = row.menu_name;
            hcCore.post({
                url: '/SysMenu/GetActions/' + me.actionInfo.menuNo 
                , param: {
                }
                , success: function (rsp) {
                    me.actionInfo.value = rsp.data.map(item => item.act_no);
                    me.actionInfo.visible = true;
                }
            });
        }
        , grantActions: function () {
            let me = this;
            hcCore.post({
                url: '/SysMenu/GrantActions?id=' + me.actionInfo.menuNo
                , param: {
                    act_nos: me.actionInfo.value.join(',')
                }
                , success: function (rsp) {
                    hcCore.showSuccess('操作成功');
                    me.actionInfo.visible = false;
                }
            });
        }
        , buildMenus: function (records, optionArr, index) {
            records.forEach(item => {
                //编辑时去除选中节点及其子节点
                if (this.edit.optype == 'edit' && this.selected.rows.length > 0 && item.menu_no == this.selected.rows[0].menu_no) {
                }
                else {
                    optionArr.push({
                        value: item.menu_no,
                        label: this.getSpace(index) + item.menu_name
                    });
                    if (item.children && item.children.length > 0) {
                        this.buildMenus(item.children, optionArr, index + 1);
                    }
                }
            });
        }
        , getParams: function () {
            let param = {};
            this.edit.fields.forEach((item, index) => {
                param[item.name] = item.value;
            });
            return param;
        }
        , getSpace: function (index) {
            let temp = '';
            for (let i = 0; i < index; i++){
                temp += '- ';
            }
            return temp;
        }
        , getSelectedRecord: function (records, id) {
            let stark = [];
            stark = stark.concat(records);
            while (stark.length > 0) {
                let temp = stark.shift();
                if (temp.children && temp.children.length) {
                    stark = stark.concat(temp.children);
                }
                if (temp.menu_no == id) {
                    return temp;
                }
            }
        }
        , getActionInfo: function () {
            let me = this;
            hcCore.post({
                url: '/SysAction/List'
                , param: {}
                , success: function (rsp) {
                    me.actionInfo.data = rsp.data.map(function (item) { return { key: item.act_no, label: item.act_name }});
                }
            });
        }
        , resetParams: function (obj) {
            obj.forEach(item => {
                item.value = '';
                item.disabled = false;
            });
        }
        , insertRecord: function (records, data) {
            let me = this;
            let record = '';
            if (data.menu_pno != '-') {
                record = me.getSelectedRecord(records, data.menu_pno);
                records = record.children;
            }

            if (records.length == 0) {
                records.push(data);
            }
            else {
                let insertIndex = 0;
                for (insertIndex = 0; insertIndex < records.length; insertIndex++) {
                    if (records[insertIndex].menu_orderby > data.menu_orderby) {
                        break;
                    }
                }
                if (insertIndex < 0) insertIndex = 0;
                records.splice(insertIndex, 0, data);
            }
            if (data.menu_pno != '-') {
                setTimeout(() => {
                    me.expandParent(record);
                }, 100);
            }
        }
        , expandParent: function (record) {
            this.$refs.tblRecords.toggleRowExpansion(record, true);
            if (record.menu_pno != '-') {
                record = this.getSelectedRecord(this.tableData.records, record.menu_pno);
                this.expandParent(record);
            }
        }
        , removeSelectedRecords: function (records, ids) {
            let me = this;
            if (ids.length > 0 && records.length > 0) {
                for (let i = records.length - 1; i >= 0; i--) {
                    let index = ids.indexOf(records[i].menu_no);
                    if (index > -1) {
                        records.splice(i, 1);
                        ids.splice(index, 1);
                    }
                    else {
                        if (records[i] && records[i].children && records[i].children.length > 0) {
                            me.removeSelectedRecords(records[i].children, ids);
                        }
                    }
                }
            }
        }
    }
});